#include <print_error.h>

#include <boost/filesystem/path.hpp>
#include <boost/filesystem/convenience.hpp>
#include <boost/lexical_cast.hpp>
// link with -lboost_filesystem-gcc

#include <string>
#include <algorithm>
#include <fstream>
#include <stdexcept>
using std::ofstream;
using std::min;
using std::string;
using std::exception;
using boost::filesystem::path;
using boost::filesystem::extension;
using boost::filesystem::basename;
using boost::lexical_cast;

#include "open_stream_name_with_subscript.h"

void open_stream_with_subscript(ofstream& ostrm, const string& base_file_name,
									unsigned index, std::size_t subscript_width)
{
	string subscript = lexical_cast<string>(index);
	subscript = string(subscript_width - min(subscript.length(), subscript_width - 1),
							'-') + subscript;

	open_stream_with_subscript(ostrm, base_file_name, subscript);
}


void open_stream_with_subscript(ofstream& ostrm, const string& base_file_name,
									const string& subscript)
{
	// file must have name
	if (!base_file_name.length())
		throw std::logic_error("Could not open a file with no name!");



	// odd this is open.
	if (ostrm.is_open())
		 ostrm.close();

	// try open
	try
	{
		path orig_path(base_file_name, boost::filesystem::native);
		path newname(orig_path.branch_path());
		newname /= path(basename(orig_path) + subscript + extension(orig_path),
						boost::filesystem::native);
		ostrm.open(newname.string().c_str());
	}
	catch (exception const & e)
	{
		throw std::runtime_error("Could not open the file (" + base_file_name + "). "
								"This is not a valid path.\n");
	}

	// is open?
	if (!ostrm.good())
		throw std::runtime_error("Could not open the file (" + base_file_name + ").\n");
}



